package com.gzxw.mogublog.xo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzxw.mogublog.base.enums.EMenuType;
import com.gzxw.mogublog.commons.entity.CategoryMenu;
import com.gzxw.mogublog.utils.StringUtils;
import com.gzxw.mogublog.xo.mapper.CategoryMenuMapper;
import com.gzxw.mogublog.xo.service.CategoryMenuService;
import com.gzxw.mogublog.xo.vo.CategoryMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CategoryMenuServiceImpl extends ServiceImpl<CategoryMenuMapper, CategoryMenu> implements CategoryMenuService {

    @Autowired
    private CategoryMenuMapper categoryMenuMapper;

    @Override
    public List<CategoryMenu> getAllMenuByIds(String[] categoryId) {

        categoryMenuMapper.selectBatchIds(Arrays.asList(categoryId));

        return categoryMenuMapper.selectBatchIds(Arrays.asList(categoryId));
    }

    @Override
    public IPage<CategoryMenu> getPageList(CategoryMenuVO categoryMenuVO) {

        QueryWrapper<CategoryMenu> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(categoryMenuVO.getKeyword()) && !StringUtils.isEmpty(categoryMenuVO.getKeyword().trim())) {
            queryWrapper.like("name", categoryMenuVO.getKeyword().trim());
        }
        if (categoryMenuVO.getMenuLevel() != 0) {
            queryWrapper.eq("menu_level", categoryMenuVO.getMenuLevel());
        }

        Page<CategoryMenu> page = new Page<>();
        page.setCurrent(categoryMenuVO.getCurrentPage());
        page.setSize(categoryMenuVO.getPageSize());
        queryWrapper.eq("status", 1);
        queryWrapper.orderByDesc("sort");
        IPage<CategoryMenu> pageList = this.page(page, queryWrapper);
        List<CategoryMenu> list = pageList.getRecords();

        List<String> ids = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getParentUid())) {
                ids.add(item.getParentUid());
            }
        });

        if (ids.size() > 0) {
            Collection<CategoryMenu> parentList = this.listByIds(ids);
            Map<String, CategoryMenu> map = new HashMap<>();
            parentList.forEach(item -> {
                map.put(item.getUid(), item);
            });
            list.forEach(item -> {
                item.setParentCategoryMenu(map.get(item.getParentUid()));
            });
        }
        pageList.setRecords(list);
        return pageList;
    }

    @Override
    public List<CategoryMenu> getAllList(String keyword) {
        QueryWrapper<CategoryMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_level", "1");
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.eq("uid", keyword);
        }

        queryWrapper.orderByDesc("sort");
        queryWrapper.eq("status", 1);
        queryWrapper.eq("menu_type", EMenuType.MENU);
        List<CategoryMenu> list = this.list(queryWrapper); // 不进行分页

        //获取所有的ID，去寻找他的子目录
        List<String> ids = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getUid())) {
                ids.add(item.getUid());
            }
        });

        QueryWrapper<CategoryMenu> childWrapper = new QueryWrapper<>();
        childWrapper.in("parent_uid", ids); // 存在父id，说明至少是二级菜单
        childWrapper.eq("status", 1);
        Collection<CategoryMenu> childList = this.list(childWrapper); // 所有的二级菜单
        //获取所有的二级菜单，去寻找他的子按钮
        List<String> secondMenuUids = new ArrayList<>(); // 二级菜单的id
        childList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getUid())) {
                secondMenuUids.add(item.getUid());
            }
        });

        QueryWrapper<CategoryMenu> buttonWrapper = new QueryWrapper<>();
        buttonWrapper.in("parent_uid", secondMenuUids);
        buttonWrapper.eq("status", 1);
        Collection<CategoryMenu> buttonList = this.list(buttonWrapper); //三级按钮

        Map<String, List<CategoryMenu>> map = new HashMap<>();

        buttonList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getParentUid())) {
                if (map.get(item.getParentUid()) != null) {
                    List<CategoryMenu> categoryMenus = map.get(item.getParentUid());
                    categoryMenus.add(item);
                    map.put(item.getParentUid(), categoryMenus);
                } else {
                    List<CategoryMenu> newList = new ArrayList<>();
                    newList.add(item);
                    map.put(item.getParentUid(), newList);
                }
            }
        });
        // 二级菜单下设置三级按钮
        childList.forEach(item -> {
            if (map.get(item.getUid()) != null) {
                List<CategoryMenu> categoryMenus = map.get(item.getUid());
                // 进行排序
                categoryMenus.sort((o1, o2) -> {
                    if (o1.getSort() > o2.getSort()) {
                        return -1;
                    } else if (o1.getSort().equals(o2.getSort())) {
                        return 0;
                    } else {
                        return 1;
                    }
                });
                item.setChildCategoryMenu(categoryMenus);
            }
        });

        // 给一级菜单设置二级菜单
        list.forEach(item -> {
            List<CategoryMenu> secondList = new ArrayList<>();
            childList.forEach(second -> {
                if (second.getParentUid().equals(item.getUid())) {
                    secondList.add(second);
                }
            });
            Collections.sort(secondList);
            item.setChildCategoryMenu(secondList);
        });

        return list;
    }

    @Override
    public List<CategoryMenu> getButtonAllList(String keyword) {

        QueryWrapper<CategoryMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_level", "2");
        queryWrapper.orderByDesc("sort");
        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.eq("uid", keyword);
        }
        queryWrapper.eq("status", 1);
        queryWrapper.eq("menu_type", EMenuType.MENU);
        List<CategoryMenu> list = this.list(queryWrapper); // 所有的二级菜单

        // 获取所有二级菜单下的uid，去寻找他的子目录
        List<String> secondUids = new ArrayList<>();
        list.forEach(item -> {
            secondUids.add(item.getUid());
        });

        QueryWrapper<CategoryMenu> childWrapper = new QueryWrapper<>();
        childWrapper.in("parent_uid", secondUids);
        childWrapper.eq("status", 1);
        Collection<CategoryMenu> childList = this.list(childWrapper);

        Map<String, List<CategoryMenu>> secondChildMap = new HashMap<>();
        childList.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getParentUid())) {
                if (secondChildMap.get(item.getParentUid()) != null) {
                    List<CategoryMenu> categoryMenus = secondChildMap.get(item.getParentUid());
                    categoryMenus.add(item);
                    secondChildMap.put(item.getParentUid(), categoryMenus);
                } else {
                    List<CategoryMenu> categoryMenus = new ArrayList<>();
                    categoryMenus.add(item);
                    secondChildMap.put(item.getParentUid(), categoryMenus);
                }
            }
        });

        // 为二级菜单设置三级子按钮
        list.forEach(item -> {
            if (secondChildMap.get(item.getUid()) != null) {
                List<CategoryMenu> categoryMenus = secondChildMap.get(item.getUid());
                Collections.sort(categoryMenus);
                item.setChildCategoryMenu(categoryMenus);
            }
        });
        return list;
    }

    @Override
    public String addCategoryMenu(CategoryMenuVO categoryMenuVO) {

        if (categoryMenuVO.getMenuLevel() == 1) {
            categoryMenuVO.setMenuLevel(null);
        }
        CategoryMenu categoryMenu = new CategoryMenu();
        categoryMenu.setParentUid(categoryMenuVO.getParentUid());
        categoryMenu.setSort(categoryMenuVO.getSort());
        categoryMenu.setIcon(categoryMenuVO.getIcon());
        categoryMenu.setSummary(categoryMenuVO.getSummary());
        categoryMenu.setMenuLevel(categoryMenuVO.getMenuLevel());
        categoryMenu.setMenuType(categoryMenuVO.getMenuType());
        categoryMenu.setName(categoryMenuVO.getName());
        categoryMenu.setUrl(categoryMenuVO.getUrl());
        categoryMenu.setIsShow(categoryMenuVO.getIsShow());
        categoryMenu.setUpdateTime(new Date());
        categoryMenu.setIsJumpExternalUrl(categoryMenuVO.getIsJumpExternalUrl());
        categoryMenu.insert();

        return "添加成功";
    }

    @Override
    public String editCategoryMenu(CategoryMenuVO categoryMenuVO) {
        CategoryMenu categoryMenu = this.getById(categoryMenuVO.getUid());
        categoryMenu.setParentUid(categoryMenuVO.getParentUid());
        categoryMenu.setSort(categoryMenuVO.getSort());
        categoryMenu.setIcon(categoryMenuVO.getIcon());
        categoryMenu.setSummary(categoryMenuVO.getSummary());
        categoryMenu.setMenuLevel(categoryMenuVO.getMenuLevel());
        categoryMenu.setMenuType(categoryMenuVO.getMenuType());
        categoryMenu.setName(categoryMenuVO.getName());
        categoryMenu.setUrl(categoryMenuVO.getUrl());
        categoryMenu.setIsShow(categoryMenuVO.getIsShow());
        categoryMenu.setUpdateTime(new Date());
        categoryMenu.setIsJumpExternalUrl(categoryMenuVO.getIsJumpExternalUrl());
        categoryMenu.updateById();
        // 修改成功后，需要删除redis中所有的admin访问路径
        return "修改成功";
    }

    @Override
    public String deleteCategoryMenu(CategoryMenuVO categoryMenuVO) {

        // 删除二级菜单，删除时，若存在三级按钮，则无法删除
        QueryWrapper<CategoryMenu> categoryMenuQueryWrapper = new QueryWrapper<>();
        categoryMenuQueryWrapper.eq("status", 1);
        categoryMenuQueryWrapper.in("parent_uid", categoryMenuVO.getUid());
        int count = this.count(categoryMenuQueryWrapper);
        if (count > 0) {
            return "该菜单下还有子菜单";
        }
        CategoryMenu categoryMenu = this.getById(categoryMenuVO.getUid());
        categoryMenu.setStatus(0);
        categoryMenu.setUpdateTime(new Date());
        categoryMenu.updateById();
        return "删除成功";
    }

    @Override
    public String stickCategoryMenu(CategoryMenuVO categoryMenuVO) {

        // 查询出sort最大的值
        QueryWrapper<CategoryMenu> categoryMenuQueryWrapper = new QueryWrapper<>();
        categoryMenuQueryWrapper.eq("status", 1);
        categoryMenuQueryWrapper.orderByDesc("sort");
        categoryMenuQueryWrapper.last("limit 1");

        CategoryMenu maxSortMenu = this.getOne(categoryMenuQueryWrapper);
        // 判断该菜单是否已经顶置
        if (maxSortMenu.getName().equals(categoryMenuVO.getName())) {
            return "该菜单已经顶置";
        }

        CategoryMenu categoryMenu = this.getById(categoryMenuVO.getUid());

        int maxSort = maxSortMenu.getSort() + 1;

        categoryMenu.setSort(maxSort);

        categoryMenu.updateById();

        return "更新成功";
    }
}
